package 递归;

public class 迷宫回溯 {
    public static void main(String[] args) {
        // 1代表隔板，2代表已走过 3代表无路可走
        int map[][] = new int[8][7];
        for (int i = 0; i < map[0].length; i++) {
            map[0][i] = 1;
            map[map.length - 1][i] = 1;
        }
        for (int i = 0; i < map.length; i++) {
            map[i][0] = 1;
            map[i][map[0].length - 1] = 1;
        }
        map[3][1] = 1;
        map[3][2] = 1;

        for (int[] row : map) {
            for (int num : row) {
                System.out.print(num + "\t");
            }
            System.out.println();
        }

        isGoway2(map, 1, 1);
        System.out.println();
        for (int[] row : map) {
            for (int num : row) {
                System.out.print(num + "\t");
            }
            System.out.println();
        }

    }

    public static boolean isGoway(int[][] map, int i, int j) { // 能走到右下角再返回true，否则返回false
        if (map[6][5] == 2) {
            return true;
        }
        if (map[i][j] == 0) {
            map[i][j] = 2;
            if (isGoway(map, i + 1, j)) {
                return true;
            }
            if (isGoway(map, i, j + 1)) {
                return true;
            }
            if (isGoway(map, i - 1, j)) {
                return true;
            }
            if (isGoway(map, i, j - 1)) {
                return true;
            }
            if (!isGoway(map, i + 1, j) && !isGoway(map, i, j + 1) && !isGoway(map, i - 1, j) && !isGoway(map, i, j - 1)) {
                map[i][j] = 3;
                return false;
            }
        }
        // 如果不等于0，也就是=1是隔板，=2是走过的路，=3是无路可走
        return false;
    }

    public static boolean isGoway2(int[][] map, int i, int j) { // 能走到右下角再返回true，否则返回false
        if (map[6][5] == 2) {
            return true;
        }
        if (map[i][j] == 0) {
            map[i][j] = 2;
            if (isGoway2(map, i - 1, j)) {
                return true;
            }
            if (isGoway2(map, i, j + 1)) {
                return true;
            }
            if (isGoway2(map, i + 1, j)) {
                return true;
            }
            if (isGoway2(map, i - 1, j - 1)) {
                return true;
            }
            if (!isGoway2(map, i + 1, j) && !isGoway(map, i, j + 1) && !isGoway(map, i - 1, j) && !isGoway(map, i, j - 1)) {
                map[i][j] = 3;
                return false;
            }
        }
        // 如果不等于0，也就是=1是隔板，=2是走过的路，=3是无路可走
        return false;
    }
}
